﻿using LedProject.Devices;
using LedProject.Logger;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace LedProject
{
    public class Core
    {
        
        
        //控制灯亮和熄灭的回调函数
        internal event Action<bool> LedOpenOrClose;
        internal event Action<int> LedSlide;

        internal string ipBegin = "192.168.1.";
        //led 灯的列表
        internal List<LedDevice> ledDevices = new List<LedDevice>();
        internal Core() {

        }

        //初始化设备
        internal void InitLedDevice()
        {
            Task.Run(() =>
            {
                while (true)
                {
                    Parallel.For(2, 255, (i) =>
                    {
                        string ip = $"{ipBegin}{i}";
                        if (ledDevices.Exists(t => t.ipStr == ip))
                            return;
                        //如果不存在该ip ,尝试连接
                        LedDevice device = new LedDevice() { ipStr = ip };
                        Ping pingSender = new Ping();
                        PingReply reply = pingSender.Send(ip,500);

                        if (reply.Status != IPStatus.Success)
                        {
                            return;
                        }
                        device.tcpClient.BeginConnect(ip, 10086,new AsyncCallback(ConnectCallBack), device);
                    });
                    Thread.Sleep(5000);
                }
            });

        }

        //设备连接成功回调
        internal void ConnectCallBack(IAsyncResult ar)
        {
            if (ar.IsCompleted)
            {
                var dev =ar.AsyncState as LedDevice;
                try
                {
                    dev.tcpClient.EndConnect(ar);
                }
                catch (Exception)
                {
                    return;
                }
                if (!dev.tcpClient.Connected)
                {
                    dev.tcpClient.Close();
                    return;
                }
                if (ledDevices.Exists(t => t.ipStr == dev.ipStr))
                {
                    dev.tcpClient.Close();
                    return;
                }
                LedOpenOrClose += dev.OpenOrCloseLight;
                LedSlide += dev.OpenLight;
                dev.CloseLight();
                ledDevices.Add(dev);
                Log.Info($"LED({dev.ipStr})连接成功");
            }
        }

        //控制灯的亮灭
        internal void LedOpenOrCloseFunc(bool state)
        {
            LedOpenOrClose?.Invoke(state);
        }

        internal void LedSlideFunc(int Pwm)
        {
            LedSlide?.Invoke(Pwm);
        }
    }
}
